/**
 * Copyright &copy; 2012-2013 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package com.microservice.base.common.utils;

import java.io.UnsupportedEncodingException;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

/**
 * 字符串工具类, 继承org.apache.commons.lang3.StringUtils类
 * @author ThinkGem
 * @version 2013-05-22
 */
public class StringUtils extends org.apache.commons.lang3.StringUtils {
    public static Logger logger = Logger.getLogger(StringUtils.class);

    private static final String CHARSET_NAME = "UTF-8";

    public static String lowerFirst(String str) {
        if (StringUtils.isBlank(str)) {
            return "";
        } else {
            return str.substring(0, 1).toLowerCase() + str.substring(1);
        }
    }

    public static String upperFirst(String str) {
        if (StringUtils.isBlank(str)) {
            return "";
        } else {
            return str.substring(0, 1).toUpperCase() + str.substring(1);
        }
    }

    /**
     * 转换为字节数组
     *
     * @param byte
     * @return
     */
    public static String toString(byte[] bytes) {
        try {
            return new String(bytes, CHARSET_NAME);
        } catch (UnsupportedEncodingException e) {
            return EMPTY;
        }
    }

    /**
     * 转换为字节数组
     * @param str
     * @return
     */
    public static byte[] getBytes(String str) {
        if (str != null) {
            try {
                return str.getBytes(CHARSET_NAME);
            } catch (UnsupportedEncodingException e) {
                return null;
            }
        } else {
            return null;
        }
    }

    /**
     * 替换掉HTML标签方法
     */
    public static String replaceHtml(String html) {
        if (isBlank(html)) {
            return "";
        }
        String regEx = "<.+?>";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(html);
        String s = m.replaceAll("");
        return s;
    }

    /**
     * 缩略字符串（不区分中英文字符）
     * @param str 目标字符串
     * @param length 截取长度
     * @return
     */
    public static String abbr(String str, int length) {
        if (str == null) {
            return "";
        }
        try {
            StringBuilder sb = new StringBuilder();
            int currentLength = 0;
            for (char c : str.toCharArray()) {
                currentLength += String.valueOf(c).getBytes("GBK").length;
                if (currentLength <= length - 3) {
                    sb.append(c);
                } else {
                    sb.append("...");
                    break;
                }
            }
            return sb.toString();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 转换为Double类型
     */
    public static Double toDouble(Object val) {
        if (val == null) {
            return 0D;
        }
        try {
            return Double.valueOf(trim(val.toString()));
        } catch (Exception e) {
            return 0D;
        }
    }

    /**
     * 转换为Float类型
     */
    public static Float toFloat(Object val) {
        return toDouble(val).floatValue();
    }

    /**
     * 转换为Long类型
     */
    public static Long toLong(Object val) {
        return toDouble(val).longValue();
    }

    /**
     * 转换为Integer类型
     */
    public static Integer toInteger(Object val) {
        return toLong(val).intValue();
    }

    /**
     * 获得用户远程地址
     */
    public static String getRemoteAddr(HttpServletRequest request) {
        String remoteAddr = request.getHeader("X-Real-IP");
        if (isNotBlank(remoteAddr)) {
            remoteAddr = request.getHeader("X-Forwarded-For");
        } else if (isNotBlank(remoteAddr)) {
            remoteAddr = request.getHeader("Proxy-Client-IP");
        } else if (isNotBlank(remoteAddr)) {
            remoteAddr = request.getHeader("WL-Proxy-Client-IP");
        }
        return remoteAddr != null ? remoteAddr : request.getRemoteAddr();
    }

    /**
     * 创建指定数量的随机字符串
     *
     * @param numberFlag
     *            是否是数字
     * @param length
     * @return
     */
    public static String createRandom(boolean numberFlag, int length) {
        String retStr = null;
        String strTable = numberFlag ? "1234567890" : "1234567890";
        int len = strTable.length();
        boolean bDone = true;
        do {
            retStr = "";
            int count = 0;
            for (int i = 0; i < length; i++) {
                double dblR = Math.random() * len;
                int intR = (int) Math.floor(dblR);
                char c = strTable.charAt(intR);
                if (('0' <= c) && (c <= '9')) {
                    count++;
                }
                retStr += strTable.charAt(intR);
            }
            if (count >= 2) {
                bDone = false;
            }
        } while (bDone);

        return retStr;
    }

    /**
     * 对象转换字符串
     * @param obj
     * @return
     */
    public static String getStr(Object obj) {
        if (obj == null) {
            return "";
        } else {
            String str = obj.toString();
            if (str == null) {
                return "";
            } else {
                return str.trim();
            }
        }
    }

    /**
     * 生成验证码
     * @return
     */
    public static String createCharacter() {
        char[] codeSeq = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J',
                'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
                'X', 'Y', 'Z', '2', '3', '4', '5', '6', '7', '8', '9'};
        Random random = new Random();
        StringBuilder s = new StringBuilder();
        for (int i = 0; i < 4; i++) {
            String r = String.valueOf(codeSeq[random.nextInt(codeSeq.length)]);//random.nextInt(10));
            s.append(r);
        }
        return s.toString();
    }

    /**
     * 创建数字字符串
     * @param len
     * @return
     */
    public static String createNumber(int len) {
        char[] codeSeq = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
        Random random = new Random();
        StringBuilder s = new StringBuilder();
        for (int i = 0; i < len; i++) {
            String r = String.valueOf(codeSeq[random.nextInt(codeSeq.length)]);//random.nextInt(10));
            s.append(r);
        }
        return s.toString();
    }

    /**
     * isRealBlank
     * @param str
     * @return
     */
    public static boolean isRealBlank(String str) {
        boolean flag;
        if (str == null || StringUtils.isBlank(str) || ("null").equals(str) || "(null)".equals(str) || str.equals("")) {
            flag = true;
        } else {
            flag = false;
        }
        return flag;
    }

    /**
     * replaceBlank(去除字符串中的空格、回车、换行符、制表符)
     * @Title: replaceBlank
     * @author :admin
     * @Description: TODO
     * @param @param str
     * @param @return    设定文件
     * @return String    返回类型
     * @throws
     */
    public static String replaceBlank(String str) {
        String dest = "";
        if (str != null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
        }
        return dest;
    }

    /**
     * 手机号验证
     *
     * @param  str
     * @return 验证通过返回true
     */
    public static boolean isMobile(String str) {
//    	if (isBlank(str)) {
//			return false;
//		}
//    	if (str.length() > 20||str.length() < 11) {
//			return false;
//		}
//    	if (str.length() == 11) {
        Pattern p = null;
        Matcher m = null;
        boolean b = false;
        p = Pattern.compile("^[1][3,4,5,7,8][0-9]{9}$"); // 验证手机号
        m = p.matcher(str);
        b = m.matches();
        return b;
//		}
//        return true;
    }

    /**
     * 检查整数
     * @param num
     * @param type
     * 		"0+" :非负整数
     * 		"+"  :正整数
     * 		"-0" :非正整数
     * 		"-"  :负整数
     * 		""   :整数
     * @return
     */
    public static boolean checkNumber(String num, String type) {
        if (num == null) {
            return false;
        }
        String eL = "";
        if (type.equals("0+")) eL = "^\\d+$";//非负整数
        else if (type.equals("+")) eL = "^\\d*[1-9]\\d*$";//正整数
        else if (type.equals("-0")) eL = "^((-\\d+)|(0+))$";//非正整数
        else if (type.equals("-")) eL = "^-\\d*[1-9]\\d*$";//负整数
        else eL = "^-?\\d+$";//整数
        Pattern p = Pattern.compile(eL);
        Matcher m = p.matcher(num);
        boolean b = m.matches();
        return b;
    }

    /**
     * 获取字符串长度，中文字符长度为2
     * @param s
     * @return
     */
    public static int length(String s) {
        if (s == null)
            return 0;
        char[] c = s.toCharArray();
        int len = 0;
        for (int i = 0; i < c.length; i++) {
            len++;
            if (!isLetter(c[i])) {
                len++;
            }
        }
        return len;
    }

    /**
     * 判断是否是中文字符
     * @param c
     * @return
     */
    public static boolean isLetter(char c) {
        int k = 0x80;
        return c / k == 0 ? true : false;
    }

    /**
     * freemarkerProcess(将字符串转换成模板，替换字符串)
     *
     * @Title: freemarkerProcess
     * @author :admin
     * @Description: 将字符串转换成模板，替换字符串
     * @param @param input
     * @param @param templateStr
     * @param @return    设定文件
     * @return String    返回类型
     * @throws
     */
//    public static String freemarkerProcess(Map input, String templateStr) {
//        StringTemplateLoader stringLoader = new StringTemplateLoader();
//        String template = "content";
//        stringLoader.putTemplate(template, templateStr);
//        Configuration cfg = new Configuration();
//        cfg.setTemplateLoader(stringLoader);
//        try {
//            Template templateCon = cfg.getTemplate(template);
//            StringWriter writer = new StringWriter();
//            templateCon.process(input, writer);
//            return writer.toString();
//        } catch (IOException e) {
//        	logger.error("素材渲染时"+e);
//            e.printStackTrace();
//        } catch (TemplateException e) {
//        	logger.error("素材渲染时"+e);
//            e.printStackTrace();
//        }
//        return templateStr;
//    }

    /**
     * 处理数字显示
     * @param str
     * @return
     */
    public static String getNumberFormatter(String str) {
        String number = "";
        if (str.indexOf(".") != -1) {
            String fieldId = str.substring(0, str.indexOf("."));//新的字段id
            String fieldName = str.substring(str.indexOf(".") + 1, str.length());//字段
            if (fieldName.equals("0") || fieldName.equals("00") || Long.parseLong(fieldName) == 0) {
                number = fieldId;
            } else {
                number = str;
            }
        } else {
            number = str;
        }
        return number;
    }
}
